import { useState, useEffect } from 'react';
import { message } from 'antd';
import { Department, DepartmentMember, DepartmentForm } from '../../types/rbac';
import { departmentApi } from '../../services/cloud/api/departmentApi';
import { useAsyncState } from '../common/useErrorHandler';

// 综合部门管理 Hook
export const useDepartments = (params?: {
  parentId?: string;
  keyword?: string;
  status?: number;
  autoLoad?: boolean;
}) => {
  const [departments, setDepartments] = useState<Department[]>([]);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [departmentManagers, setDepartmentManagers] = useState<any[]>([]);
  
  // 使用统一的异步状态管理
  const { executeAsync, getLoading, hasError, error, clearError } = useAsyncState();

  // 加载部门列表
  const loadDepartments = async (keyword?: string) => {
    const result = await executeAsync('loadDepartments', async () => {
      const response = await departmentApi.getDepartments({
        parentId: params?.parentId,
        keyword: keyword || searchKeyword,
        status: params?.status,
        current: 1,
        size: 1000
      });
      
      const departmentList = response.records || [];
      setDepartments(departmentList);
      setTotal(response.total || departmentList.length);
      
      return departmentList;
    }, {
      customErrorMessage: '获取部门列表失败'
    });
    
    return result;
  };

  // 加载部门管理员
  const loadDepartmentManagers = async () => {
    const result = await executeAsync('loadDepartmentManagers', async () => {
      const response = await departmentApi.getDepartmentManagers();
      const managers = response || [];
      setDepartmentManagers(managers);
      return managers;
    }, {
      customErrorMessage: '获取部门管理员失败'
    });
    
    return result;
  };

  // 创建部门
  const createDepartment = async (departmentForm: DepartmentForm) => {
    const result = await executeAsync('createDepartment', async () => {
      const newDepartment = await departmentApi.createDepartment(departmentForm);
      message.success('部门创建成功');
      await loadDepartments(); // 重新加载列表
      return newDepartment;
    }, {
      customErrorMessage: '创建部门失败'
    });
    
    return result;
  };

  // 更新部门
  const updateDepartment = async (id: string, departmentForm: DepartmentForm) => {
    const result = await executeAsync('updateDepartment', async () => {
      const updatedDepartment = await departmentApi.updateDepartment(id, departmentForm);
      message.success('部门更新成功');
      await loadDepartments(); // 重新加载列表
      return updatedDepartment;
    }, {
      customErrorMessage: '更新部门失败'
    });
    
    return result;
  };

  // 删除部门
  const deleteDepartment = async (id: string) => {
    const result = await executeAsync('deleteDepartment', async () => {
      await departmentApi.deleteDepartment(id);
      message.success('部门删除成功');
      await loadDepartments(); // 重新加载列表
      return true;
    }, {
      customErrorMessage: '删除部门失败'
    });
    
    return result;
  };

  // 搜索处理
  const handleSearch = (keyword: string) => {
    setSearchKeyword(keyword);
    loadDepartments(keyword);
  };

  // 初始化加载
  useEffect(() => {
    if (params?.autoLoad !== false) {
      loadDepartments();
      loadDepartmentManagers();
    }
  }, [params?.parentId, params?.status]);

  // 搜索关键词变化时重新加载
  useEffect(() => {
    if (searchKeyword) {
      loadDepartments();
    }
  }, [searchKeyword]);

  return {
    // 数据状态
    departments,
    departmentManagers,
    total,
    searchKeyword,
    
    // 加载状态 - 使用统一的异步状态管理
    loading: getLoading('loadDepartments'),
    actionLoading: getLoading('createDepartment') || getLoading('updateDepartment') || getLoading('deleteDepartment'),
    
    // 错误状态
    hasError,
    error,
    clearError,
    
    // 操作方法
    loadDepartments,
    loadDepartmentManagers,
    createDepartment,
    updateDepartment,
    deleteDepartment,
    handleSearch,
    setSearchKeyword,
    
    // 刷新方法
    refresh: () => {
      loadDepartments();
      loadDepartmentManagers();
    },
  };
};

// 部门树管理
export const useDepartmentTree = (autoLoad = true) => {
  const [departmentTree, setDepartmentTree] = useState<Department[]>([]);
  const [loading, setLoading] = useState(false);

  const loadDepartmentTree = async () => {
    setLoading(true);
    try {
      const tree = await departmentApi.getDepartmentTree();
      setDepartmentTree(tree);
    } catch (error) {
      message.error('加载部门树失败');
      console.error('Load department tree error:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (autoLoad) {
      loadDepartmentTree();
    }
  }, [autoLoad]);

  return {
    departmentTree,
    loading,
    refresh: loadDepartmentTree,
  };
};

// 部门详情管理
export const useDepartment = (departmentId?: string) => {
  const [department, setDepartment] = useState<Department | null>(null);
  const [loading, setLoading] = useState(false);

  const loadDepartment = async (id: string) => {
    setLoading(true);
    try {
      const dept = await departmentApi.getDepartment(id);
      setDepartment(dept);
    } catch (error) {
      message.error('加载部门详情失败');
      console.error('Load department error:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (departmentId) {
      loadDepartment(departmentId);
    }
  }, [departmentId]);

  return {
    department,
    loading,
    loadDepartment,
  };
};

// 部门操作管理
export const useDepartmentActions = () => {
  const [loading, setLoading] = useState(false);

  const createDepartment = async (data: DepartmentForm): Promise<Department> => {
    setLoading(true);
    try {
      const department = await departmentApi.createDepartment(data);
      return department;
    } catch (error: any) {
      message.error(error.message || '创建部门失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateDepartment = async (id: string, data: Partial<DepartmentForm>): Promise<Department> => {
    setLoading(true);
    try {
      const department = await departmentApi.updateDepartment(id, data);
      return department;
    } catch (error: any) {
      message.error(error.message || '更新部门失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteDepartment = async (id: string): Promise<void> => {
    setLoading(true);
    try {
      await departmentApi.deleteDepartment(id);
    } catch (error: any) {
      message.error(error.message || '删除部门失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    createDepartment,
    updateDepartment,
    deleteDepartment,
  };
};

// 部门成员管理
export const useDepartmentMembers = (
  departmentId?: string,
  params?: {
    page?: number;
    size?: number;
    keyword?: string;
    autoLoad?: boolean;
  }
) => {
  const [members, setMembers] = useState<DepartmentMember[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const loadMembers = async () => {
    if (!departmentId) return;
    
    setLoading(true);
    try {
      const response = await departmentApi.getDepartmentMembers(departmentId, params);
      setMembers(response.records);
      setTotal(response.total);
    } catch (error) {
      message.error('加载部门成员失败');
      console.error('Load department members error:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (departmentId && params?.autoLoad !== false) {
      loadMembers();
    }
  }, [departmentId, params?.page, params?.size, params?.keyword]);

  return {
    members,
    loading,
    total,
    refresh: loadMembers,
  };
};

// 部门成员操作管理
export const useDepartmentMemberActions = () => {
  const [loading, setLoading] = useState(false);

  const addMember = async (departmentId: string, userIds: string[], position?: string): Promise<void> => {
    setLoading(true);
    try {
      await departmentApi.addDepartmentMember(departmentId, userIds);
    } catch (error: any) {
      message.error(error.message || '添加成员失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const removeMember = async (departmentId: string, userId: string): Promise<void> => {
    setLoading(true);
    try {
      await departmentApi.removeDepartmentMember(departmentId, userId);
    } catch (error: any) {
      message.error(error.message || '移除成员失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const setManager = async (departmentId: string, userId: string): Promise<void> => {
    setLoading(true);
    try {
      await departmentApi.setDepartmentLeader(departmentId, userId);
    } catch (error: any) {
      message.error(error.message || '设置负责人失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    addMember,
    removeMember,
    setManager,
  };
};